package cn.iocoder.yudao.module.book.service.category;

import cn.iocoder.yudao.module.book.controller.app.category.vo.AppCategoryRespVO;
import cn.iocoder.yudao.module.book.controller.app.category.vo.AppCategoryDetailRespVO;
import cn.iocoder.yudao.module.book.controller.app.category.vo.AppCollectionDetailRespVO;
import cn.iocoder.yudao.module.book.controller.app.category.vo.AppLanguageCategoriesRespVO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.time.LocalDateTime;
import cn.iocoder.yudao.module.book.controller.admin.category.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.category.CategoryDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.category.CategoryMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 分类 Service 实现类
 *
 * @author xi
 */
@Service
@Validated
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;


    @Override
    public Integer createCategory(CategorySaveReqVO createReqVO) {
        // 插入
        CategoryDO category = BeanUtils.toBean(createReqVO, CategoryDO.class);
        categoryMapper.insert(category);
        // 返回
        return category.getCategoryId();
    }

    @Override
    public void updateCategory(CategorySaveReqVO updateReqVO) {
        // 校验存在
        validateCategoryExists(updateReqVO.getCategoryId());
        // 更新前验证JSON字段格式
//        validateCategoryData(updateReqVO);
        // 更新
        CategoryDO updateObj = BeanUtils.toBean(updateReqVO, CategoryDO.class);
        categoryMapper.updateById(updateObj);
    }


    @Override
    public void deleteCategory(Integer id) {
        // 校验存在
        validateCategoryExists(id);
        // 删除
        categoryMapper.deleteById(id);
    }

//    private void validateCategoryData(CategorySaveReqVO reqVO) {
//        // 如果有collectionList字段，验证其JSON格式
//        if (reqVO.getCollectionList() != null) {
//            try {
//                // 尝试解析JSON字符串以验证其有效性
//                objectMapper.readTree(reqVO.getCollectionList());
//            } catch (Exception e) {
//                // 如果JSON格式无效，抛出异常或进行处理
//                throw new IllegalArgumentException("collectionList字段JSON格式无效: " + e.getMessage());
//            }
//        }
//    }

    private void validateCategoryExists(Integer id) {
        if (categoryMapper.selectById(id) == null) {
            throw exception(CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public CategoryDO getCategory(Integer id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public PageResult<CategoryDO> getCategoryPage(CategoryPageReqVO pageReqVO) {
        return categoryMapper.selectPage(pageReqVO);
    }

    @Override
    public AppCategoryRespVO selectByCategoryId(Integer id) {
        return categoryMapper.selectByCategoryId(id);
    }

    @Override
    public List<AppCategoryRespVO> selectByClassifyId(Integer classifyId) {
        return categoryMapper.selectByClassifyId(classifyId);
    }

    @Override
    public List<AppCategoryDetailRespVO> getCategoryDetails(Long userId) {
        // 1. 获取所有分类详情
        List<AppCategoryDetailRespVO> categories = categoryMapper.getCategoryDetailsWithCollections();
        
        // 2. 为每个分类获取绘本集详情
        for (AppCategoryDetailRespVO category : categories) {
            List<AppCollectionDetailRespVO> collections = categoryMapper.getCollectionsByCategoryId(category.getCategoryId(), userId);
            category.setCollectionsList(collections);
        }
        
        return categories;
    }
    
    /**
     * 获取指定分类下的绘本集详情
     */
    private List<AppCollectionDetailRespVO> getCollectionsByCategoryId(Integer categoryId, Long userId) {
        return categoryMapper.getCollectionsByCategoryId(categoryId, userId);
    }
    
    @Override
    public List<AppCategoryDetailRespVO> getCategoryHierarchyByClassifyId(Integer classifyId, Long userId) {
        // 1. 获取指定大分类下的所有分类详情
        List<AppCategoryDetailRespVO> categories = categoryMapper.getHierarchyByClassifyId(classifyId);
        
        // 2. 为每个分类获取绘本集详情
        for (AppCategoryDetailRespVO category : categories) {
            List<AppCollectionDetailRespVO> collections = categoryMapper.getCollectionsByCategoryId(category.getCategoryId(), userId);
            category.setCollectionsList(collections);
        }
        
        return categories;
    }
    
    @Override
    public List<java.util.Map<String, Object>> getBooksWithImagesByCollectionId(Integer collectionId) {
        return categoryMapper.getBooksWithImagesByCollectionId(collectionId);
    }
    
    @Override
    public List<AppLanguageCategoriesRespVO> getCategoriesByLanguage(Integer isEnglish) {
        // 1. 获取大分类列表
        List<java.util.Map<String, Object>> classifyList = categoryMapper.getClassifyByLanguage(isEnglish);
        
        List<AppLanguageCategoriesRespVO> result = new ArrayList<>();
        
        // 2. 为每个大分类构建完整的层级结构
        for (java.util.Map<String, Object> classifyMap : classifyList) {
            AppLanguageCategoriesRespVO classifyVO = new AppLanguageCategoriesRespVO();
            classifyVO.setClassifyId((Integer) classifyMap.get("classifyId"));
            classifyVO.setClassifyTitle((String) classifyMap.get("classifyTitle"));
            
            // 3. 获取该大分类下的所有分类
            List<java.util.Map<String, Object>> categoryList = categoryMapper.getCategoriesByClassifyAndLanguage(
                classifyVO.getClassifyId(), isEnglish);
            
            List<AppLanguageCategoriesRespVO.CategoryInfo> categoryInfoList = new ArrayList<>();
            
            for (java.util.Map<String, Object> categoryMap : categoryList) {
                AppLanguageCategoriesRespVO.CategoryInfo categoryInfo = new AppLanguageCategoriesRespVO.CategoryInfo();
                categoryInfo.setCategoryId((Integer) categoryMap.get("categoryId"));
                categoryInfo.setCategoryTitle((String) categoryMap.get("categoryTitle"));
                
                // 4. 获取该分类下的所有绘本集合（按当前用户书架过滤）
                Long currentUserId = null;
                try {
                    cn.iocoder.yudao.module.book.service.users.userDTOService us =
                        cn.iocoder.yudao.framework.common.util.spring.SpringUtils.getApplicationContext()
                          .getBean(cn.iocoder.yudao.module.book.service.users.userDTOService.class);
                    currentUserId = us.getCurrentUserId();
                } catch (Exception ignore) {}
                List<java.util.Map<String, Object>> collectionList = categoryMapper.getCollectionsByCategoryAndLanguage(
                    categoryInfo.getCategoryId(), isEnglish, currentUserId);
                
                List<AppLanguageCategoriesRespVO.CollectionInfo> collectionInfoList = new ArrayList<>();
                
                for (java.util.Map<String, Object> collectionMap : collectionList) {
                    AppLanguageCategoriesRespVO.CollectionInfo collectionInfo = new AppLanguageCategoriesRespVO.CollectionInfo();
                    collectionInfo.setCollectionId((Integer) collectionMap.get("collectionId"));
                    collectionInfo.setTitle((String) collectionMap.get("title"));
                    collectionInfo.setImage((String) collectionMap.get("image"));
                    collectionInfo.setDescription((String) collectionMap.get("description"));
                    collectionInfo.setCreator((String) collectionMap.get("creator"));
                    collectionInfo.setIsEnglish((Integer) collectionMap.get("isEnglish"));
                    collectionInfo.setIsTop((Integer) collectionMap.get("isTop"));
                    collectionInfo.setCreateTime((LocalDateTime) collectionMap.get("createTime"));
                    // 处理 isInBookshelf 字段的类型转换（数据库返回 Long，需要转换为 Integer）
                    Object isInBookshelfObj = collectionMap.get("isInBookshelf");
                    if (isInBookshelfObj instanceof Long) {
                        collectionInfo.setIsInBookshelf(((Long) isInBookshelfObj).intValue());
                    } else if (isInBookshelfObj instanceof Integer) {
                        collectionInfo.setIsInBookshelf((Integer) isInBookshelfObj);
                    } else {
                        collectionInfo.setIsInBookshelf(0); // 默认值
                    }
                    
                    // 5. 获取该绘本集合下的所有图书
                    List<java.util.Map<String, Object>> bookList = categoryMapper.getBooksByCollectionId(
                        collectionInfo.getCollectionId());
                    
                    List<AppLanguageCategoriesRespVO.BookInfo> bookInfoList = new ArrayList<>();
                    
                    for (java.util.Map<String, Object> bookMap : bookList) {
                        AppLanguageCategoriesRespVO.BookInfo bookInfo = new AppLanguageCategoriesRespVO.BookInfo();
                        bookInfo.setBookId((Integer) bookMap.get("bookId"));
                        bookInfo.setTitle((String) bookMap.get("title"));
                        bookInfo.setImage((String) bookMap.get("image"));
                        bookInfo.setSort((Integer) bookMap.get("sort"));
                        bookInfo.setCreateTime((LocalDateTime) bookMap.get("createTime"));
                        
                        bookInfoList.add(bookInfo);
                    }
                    
                    collectionInfo.setBooks(bookInfoList);
                    collectionInfoList.add(collectionInfo);
                }
                
                categoryInfo.setCollections(collectionInfoList);
                categoryInfoList.add(categoryInfo);
            }
            
            classifyVO.setCategories(categoryInfoList);

            // 追加“最近阅读”虚拟分类（每个大分类带上同一份，前端可只使用第一个）
            try {
                Long userId = cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId();
                if (userId != null) {
                    org.springframework.context.ApplicationContext ctx =
                            cn.iocoder.yudao.framework.common.util.spring.SpringUtils.getApplicationContext();
                    cn.iocoder.yudao.module.book.dal.mysql.records.RecordsMapper recordsMapper =
                            ctx.getBean(cn.iocoder.yudao.module.book.dal.mysql.records.RecordsMapper.class);
                    java.util.List<cn.iocoder.yudao.module.book.controller.app.user.vo.UserReadingStatsRespVO.ReadingRecordItem> recent =
                            recordsMapper.selectRecentReadingWithBooks(userId, 10);
                    if (recent != null && !recent.isEmpty()) {
                        List<AppLanguageCategoriesRespVO.CollectionInfo> recentCollections = new ArrayList<>();
                        for (cn.iocoder.yudao.module.book.controller.app.user.vo.UserReadingStatsRespVO.ReadingRecordItem item : recent) {
                            AppLanguageCategoriesRespVO.CollectionInfo c = new AppLanguageCategoriesRespVO.CollectionInfo();
                            // 最近阅读应当展示具体书本
                            c.setBookId(item.getId());
                            c.setTitle(item.getName());
                            c.setImage(item.getCover());
                            c.setDescription("最近阅读");
                            c.setIsEnglish(isEnglish);
                            recentCollections.add(c);
                        }
                        classifyVO.setRecentCollections(recentCollections);
                    }
                }
            } catch (Exception ignore) {}
            result.add(classifyVO);
        }
        
        return result;
    }
}